package com.example.zhanghao.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@ConfigurationProperties(prefix = "app.allowed")
public class CorsConfig implements WebMvcConfigurer {

    @Value("${app.allowed.domains:}")
    private List<String> allowedDomains;

    @Value("${spring.profiles.active:default}")
    private String activeProfile;

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        // //** 所有接口 allowCredentials 带上cookie session凭证
        CorsRegistration registration = registry.addMapping("/**")
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .maxAge(3600); // 1小时内不需要再预检（发OPTIONS请求）

        // 开发或默认环境
        if ("dev".equals(activeProfile) || "default".equals(activeProfile)) {
            registration.allowedOriginPatterns("*")
                    .allowCredentials(false);
        }
        // 生产环境严格配置
        else {
            registration.allowedOrigins(allowedDomains.toArray(new String[0]))
                    .allowCredentials(true);
        }
    }

}
